﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GDoc.Data;

namespace GDoc.Domain.Services
{
    public class DocumentService
    {
        public DocumentDefinition CreateDocumentDefinition(Account account, string name, List<FieldDefinition> fields)
        {
            IDocumentDefinitionRepository repository = RepositoryFactory.CreateDocumentDefinitionRepository();
            
            DocumentDefinition documentDefinition = new DocumentDefinition
            {
                Account = account,
                Name = name
            };

            SortFields(documentDefinition, fields);

            documentDefinition = repository.SaveOrUpdate(documentDefinition);

            return documentDefinition;
        }

        public DocumentDefinition CreateDocumentDefinition(Account account, string name)
        {
            return this.CreateDocumentDefinition(account, name, new List<FieldDefinition>());
        }

        public DocumentDefinition Save(DocumentDefinition documentDefinition)
        {
            IDocumentDefinitionRepository repository = RepositoryFactory.CreateDocumentDefinitionRepository();

            SortFields(documentDefinition);

            repository.SaveOrUpdate(documentDefinition);

            return documentDefinition;
        }

        private void SortFields(DocumentDefinition documentDefinition, List<FieldDefinition> fields = null)
        {
            if (fields == null)
                fields = new List<FieldDefinition>(documentDefinition.Fields);

            documentDefinition.Fields.Clear();

            int order = 0;
            foreach (var field in fields.OrderBy<FieldDefinition, int?>(f => f.DisplayOrder, new DisplayOrderComparer()))
            {
                order++;

                field.Document = documentDefinition;
                field.DisplayOrder = order;

                documentDefinition.Fields.Add(field);
            }
        }

    }
}
